import React, { useState } from 'react';
import { View, Text, Button, Alert, StyleSheet, TextInput } from 'react-native';
import WeChat from '../services/wechat';

const WeChatPayScreen = () => {
  const [amount, setAmount] = useState('100');
  const [isPaying, setIsPaying] = useState(false);

  const handleWeChatPay = async () => {
    setIsPaying(true);
    try {
      // 注册微信应用
      await WeChat.registerApp('YOUR_WECHAT_APP_ID');
      
      // 检查是否安装了微信
      const isInstalled = await WeChat.isWXAppInstalled();
      if (!isInstalled) {
        Alert.alert('提示', '请先安装微信');
        return;
      }
      
      // 构造支付参数（这里需要从后端获取真实的支付参数）
      const payload = {
        appId: 'YOUR_WECHAT_APP_ID',
        partnerId: 'YOUR_PARTNER_ID',
        prepayId: 'YOUR_PREPAY_ID',
        nonceStr: 'YOUR_NONCE_STR',
        timeStamp: Date.now().toString(),
        sign: 'YOUR_SIGN'
      };
      
      // 执行微信支付
      const result = await WeChat.pay(payload);
      console.log('微信支付结果:', result);
      Alert.alert('支付成功', '支付已完成');
    } catch (error) {
      console.error('微信支付失败:', error);
      Alert.alert('支付失败', error.message || '微信支付失败');
    } finally {
      setIsPaying(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>微信支付</Text>
      
      <View style={styles.amountContainer}>
        <Text style={styles.label}>支付金额:</Text>
        <TextInput
          style={styles.input}
          value={amount}
          onChangeText={setAmount}
          keyboardType="numeric"
        />
        <Text style={styles.currency}>元</Text>
      </View>
      
      <Button 
        title={isPaying ? "支付中..." : "微信支付"} 
        onPress={handleWeChatPay} 
        disabled={isPaying}
        color="#07c160"
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    justifyContent: 'center'
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 30
  },
  amountContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 30,
    justifyContent: 'center'
  },
  label: {
    fontSize: 18,
    marginRight: 10
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: 5,
    padding: 10,
    width: 100,
    textAlign: 'center',
    fontSize: 18
  },
  currency: {
    fontSize: 18,
    marginLeft: 10
  }
});

export default WeChatPayScreen;